// ==UserScript==
// @name         豆包音乐提取器
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  在豆包音乐分享页面自动提取音频URL并提供下载按钮
// @author       You
// @match        https://www.doubao.com/music-sharing?*
// @icon         
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    console.log('豆包音乐提取器已启动');

    // 创建下载按钮
    function createDownloadButton(audioUrl, filename) {
        // 移除已存在的按钮
        const existingButton = document.getElementById('doubao-music-download-btn');
        if (existingButton) existingButton.remove();

        // 创建按钮元素
        const button = document.createElement('button');
        button.id = 'doubao-music-download-btn';
        button.innerText = '🎵 下载音乐';
        button.style.cssText = `
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            border: none;
            padding: 12px 24px;
            font-size: 16px;
            font-weight: bold;
            border-radius: 8px;
            cursor: pointer;
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            transition: all 0.3s ease;
        `;

        button.onmouseover = function() {
            button.style.transform = 'translateY(-2px)';
            button.style.boxShadow = '0 6px 12px rgba(0,0,0,0.3)';
        };

        button.onmouseout = function() {
            button.style.transform = 'translateY(0)';
            button.style.boxShadow = '0 4px 8px rgba(0,0,0,0.2)';
        };

        button.onclick = function() {
            if (audioUrl) {
                console.log('开始下载音频:', audioUrl);
                const a = document.createElement('a');
                a.href = audioUrl;
                a.download = filename || 'doubao_music.mp3';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                
                // 显示成功消息
                showNotification('下载已开始!', 'success');
            } else {
                showNotification('未找到音频URL，请刷新页面重试', 'error');
            }
        };

        document.body.appendChild(button);
        return button;
    }

    // 显示通知
    function showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.innerText = message;
        notification.style.cssText = `
            position: fixed;
            top: 80px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 6px;
            color: white;
            font-weight: bold;
            z-index: 10000;
            opacity: 0;
            transition: opacity 0.3s ease;
        `;

        // 设置不同类型的样式
        if (type === 'success') {
            notification.style.background = 'rgba(76, 175, 80, 0.9)';
        } else if (type === 'error') {
            notification.style.background = 'rgba(244, 67, 54, 0.9)';
        } else {
            notification.style.background = 'rgba(33, 150, 243, 0.9)';
        }

        document.body.appendChild(notification);
        
        // 淡入效果
        setTimeout(() => {
            notification.style.opacity = '1';
        }, 10);

        // 3秒后淡出并移除
        setTimeout(() => {
            notification.style.opacity = '0';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }

    // 获取页面上的音频信息
    function getAudioInfo() {
        // 尝试从标题获取音乐信息
        const title = document.title;
        let artist = '豆包';
        let musicTitle = '未知音乐';
        
        // 从标题中提取信息
        if (title) {
            musicTitle = title.replace('音乐分享 - 豆包', '').trim();
        }
        
        // 尝试从页面内容获取艺术家和标题
        const metaTags = document.querySelectorAll('meta[property="og:title"], meta[property="twitter:title"]');
        metaTags.forEach(tag => {
            const content = tag.getAttribute('content');
            if (content && content.includes('-')) {
                const parts = content.split('-').map(p => p.trim());
                if (parts.length >= 2) {
                    artist = parts[0];
                    musicTitle = parts.slice(1).join('-');
                }
            }
        });
        
        return { artist, musicTitle };
    }

    // 尝试多种方法提取音频URL
    function extractAudioUrl() {
        console.log('开始提取音频URL...');
        
        // 方法1: 查找音频标签
        const audioElements = document.querySelectorAll('audio');
        for (const element of audioElements) {
            const src = element.getAttribute('src');
            if (src && src.startsWith('http')) {
                console.log('找到音频标签的src:', src);
                return src;
            }
        }
        
        // 方法2: 查找script标签中的音频URL
        const scripts = document.querySelectorAll('script');
        const patterns = [
            /(https?:\/\/[^"'\s]+\.mp3)/g,
            /(https?:\/\/[^"'\s]+\.m4a)/g,
            /(https?:\/\/[^"'\s]+\.wav)/g,
            /audioUrl["']\s*:\s*["'](https?:\/\/[^"']*)["']/g,
            /mp3Url["']\s*:\s*["'](https?:\/\/[^"']*)["']/g,
            /mediaUrl["']\s*:\s*["'](https?:\/\/[^"']*)["']/g
        ];
        
        for (const script of scripts) {
            const content = script.textContent || script.innerText;
            if (!content) continue;
            
            for (const pattern of patterns) {
                const matches = content.match(pattern);
                if (matches) {
                    for (const match of matches) {
                        // 清理匹配结果
                        let cleanUrl = match;
                        if (cleanUrl.includes('audioUrl') || cleanUrl.includes('mp3Url') || cleanUrl.includes('mediaUrl')) {
                            // 提取URL部分
                            const urlMatch = cleanUrl.match(/"(https?:\/\/[^"]+)"/);
                            if (urlMatch && urlMatch[1]) {
                                cleanUrl = urlMatch[1];
                            } else {
                                const urlMatch2 = cleanUrl.match(/'(https?:\/\/[^']+)'/);
                                if (urlMatch2 && urlMatch2[1]) {
                                    cleanUrl = urlMatch2[1];
                                }
                            }
                        }
                        
                        if (cleanUrl.startsWith('http') && (cleanUrl.includes('.mp3') || cleanUrl.includes('.m4a') || cleanUrl.includes('.wav'))) {
                            console.log('从脚本中提取到音频URL:', cleanUrl);
                            return cleanUrl;
                        }
                    }
                }
            }
        }
        
        // 方法3: 查找data属性
        const dataElements = document.querySelectorAll('[data-*]');
        for (const element of dataElements) {
            for (const attr of element.attributes) {
                if (attr.name.includes('audio') || attr.name.includes('media')) {
                    const value = attr.value;
                    if (value && value.startsWith('http') && (value.includes('.mp3') || value.includes('.m4a') || value.includes('.wav'))) {
                        console.log('从data属性中提取到音频URL:', value);
                        return value;
                    }
                }
            }
        }
        
        console.log('未找到音频URL');
        return null;
    }

    // 自动点击播放按钮以触发音频加载
    function triggerPlay() {
        console.log('尝试点击播放按钮...');
        const playButtons = document.querySelectorAll(
            'button:contains("播放"), button:contains("play"), ' +
            '[class*="play"], [class*="Play"], [id*="play"], [id*="Play"]'
        );
        
        if (playButtons.length > 0) {
            console.log('找到播放按钮，尝试点击...');
            playButtons[0].click();
            return true;
        }
        
        return false;
    }

    // 主函数
    function main() {
        // 尝试点击播放按钮
        triggerPlay();
        
        // 初始提取
        let audioUrl = extractAudioUrl();
        
        // 获取音乐信息
        const { artist, musicTitle } = getAudioInfo();
        const filename = `${artist} - ${musicTitle}.mp3`;
        
        // 创建下载按钮
        const button = createDownloadButton(audioUrl, filename);
        
        // 如果没找到URL，设置轮询
        if (!audioUrl) {
            showNotification('正在寻找音频源...请稍后', 'info');
            
            let attempts = 0;
            const maxAttempts = 10;
            const interval = setInterval(() => {
                attempts++;
                console.log(`尝试重新提取音频URL (${attempts}/${maxAttempts})...`);
                
                audioUrl = extractAudioUrl();
                if (audioUrl) {
                    console.log('找到音频URL!');
                    button.onclick = function() {
                        const a = document.createElement('a');
                        a.href = audioUrl;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        showNotification('下载已开始!', 'success');
                    };
                    showNotification('已找到音频源，点击按钮下载', 'success');
                    clearInterval(interval);
                } else if (attempts >= maxAttempts) {
                    console.log('达到最大尝试次数，停止搜索');
                    showNotification('无法自动找到音频源，请尝试手动操作', 'error');
                    clearInterval(interval);
                }
            }, 2000); // 每2秒尝试一次
        }
    }

    // 等待页面加载完成
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', main);
    } else {
        main();
    }
})();
